<?php
/**
 * Created by PhpStorm.
 * User: caviar
 * Date: 2019/11/1
 * Time: 16:20
 */

namespace app\common\service;

use think\cache\driver\Redis;

class LoadBalancing
{
    // 服务器地址
    const serverIps = [
        '127.0.0.1',
        '49.25.136.xx',
        '39.88.xxx.78',
        '22.xxx.178.88',
        'xx.88.333.25',
    ];

    // 随机分配Ip
    public function randAllot()
    {
        $subscript = array_rand(self::serverIps);
        return self::serverIps[$subscript];
    }


    // 均衡分配Ip
    public function balanceAllot()
    {
        $redis = new Redis();

        $len = count(self::serverIps) - CONSTANT_ONE;

        $ipNum = $redis->get('serverIp');

        if (isset($ipNum)) {
            if ($ipNum < $len) {
                $redis->set('serverIp',$ipNum + CONSTANT_ONE);
                return self::serverIps[$ipNum + CONSTANT_ONE];
            }
        }
        $redis->set('serverIp',CONSTANT_ZERO);
        return self::serverIps[CONSTANT_ZERO];
    }



}